package project_cmd

import (
	"context"
	"fmt"
	"time"

	"atomgit.com/openlinksaas/swarm_api_proxy/config"
	"atomgit.com/openlinksaas/swarm_api_proxy/utils"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/spf13/cobra"
)

var listCmd = &cobra.Command{
	Use:  "list",
	RunE: runList,
}

func runList(cmd *cobra.Command, args []string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if cfgPath == nil {
		return fmt.Errorf("miss config")
	}
	cfg, err := config.LoadProxyConfig(*cfgPath)
	if err != nil {
		return err
	}
	c, err := utils.GetDockerClient(cfg.ServerUrl, cfg.CertPath)
	if err != nil {
		return err
	}
	defer c.Close()

	filter := filters.NewArgs()
	filter.Add("label", config.PROJECT_CONFIG_KEY+"=1")
	cfgItemList, err := c.ConfigList(ctx, types.ConfigListOptions{
		Filters: filter,
	})
	if err != nil {
		return err
	}

	fmt.Println("Project List:")
	for _, cfgItem := range cfgItemList {
		fmt.Println("  ", string(cfgItem.Spec.Data))
	}
	return nil
}
